package com.haiyou.common.spring.filter;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;

import com.google.common.base.Stopwatch;
import com.haiyou.common.event.asyc.AsyncEventBuses;
import com.haiyou.common.spring.event.HttpApiLogEvent;
import com.haiyou.common.system.Properties;
import com.haiyou.common.util.ip.IpUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @Description: http 接口访问统一拦截
 * @author xingyuan
 * @date 2022年10月28日 下午3:36:33
 */

@Slf4j
public class ApiAccessFilter implements Filter{

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		
		Stopwatch stopwatch = null;
		
		if(Properties.http_api_log()) {
			stopwatch = Stopwatch.createStarted();
		}
		
		chain.doFilter(request,response);
		
		if(Properties.http_api_log()) {
			
			if(stopwatch == null) {
				return ;
			}
			
			String url = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length());
	        String ip = IpUtil.getIpAddr(httpServletRequest);
	       
	        log.debug("ip:{},url:{}",ip,url);

	        //消耗时间
			long costTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
			
			HttpApiLogEvent event = new HttpApiLogEvent();
			event.setCostTime(costTime);;
			event.setIp(ip);
			event.setUrl(url);
			event.setNodeId(Properties.server_node_id());
			event.setLocalIp(IpUtil.getLocalIP());
			
			//抛出事件 由事件处理
			AsyncEventBuses.getInstance().postEvent(event);
		}
		
	}

}
